# -*- coding: utf-8 -*-
from django.views.generic import TemplateView, FormView 
from apps.home.forms import ContactForm, LoginForm, RegisterForm 
from django.core.urlresolvers import reverse_lazy
from django.core.mail import send_mail
from .models import UserProfile , User
from django.contrib import auth
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required

class home(TemplateView): 
    template_name = 'home/home.html'
    
class contact(FormView): 
    form_class = ContactForm
    success_url = reverse_lazy('contact')
    template_name = 'home/contact_us.html'
    
    def form_valid(self, form):
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        FirstName = form.cleaned_data['FirstName']
        Email = form.cleaned_data['Email']
        Text = form.cleaned_data['Text']
        form.send_mail(FirstName, Email, Text, ['avicaz.info@gmail.com'], fail_silently=False)
        return super(contact, self).form_valid(form)
    
# class login(FormView):        
#     form_class = LoginForm
#     success_url = reverse_lazy('contact')
#     template_name = 'home/login.html'  
#     temp_succes = ''
#     
#     def form_valid(self, form):
#         username = form.cleaned_data['username']
#         password = form.cleaned_data['password']
#         user = authenticate(username=username, password=password)
#         if user is not None:
#             if user.is_active:
#                 auth.login(self.request, user)
#                 try:
#                     userP = User.objects.get(user = user.id)
#                     self.request.session['member_id'] = userP.id
#                 except:
#                     error = "Datos inválidos"
#                     
#                 if user.is_superuser:
#                     temp_succes = 'admin.views.admin_main'
#               
#             else:
#                 error = "Usuario Inactivo"
#         else:
#             error = "Datos Invalidos"
#         return super(login, self).form_valid(form)
        
class register(FormView):   
    form_class = RegisterForm
    success_url = reverse_lazy('login') 
    template_name = 'home/register.html' 
    
    
    def form_valid(self, form):  
        user = form.save(commit=False)
        profile = UserProfile()
        profile.address = form.cleaned_data['address']
        profile.addressSend = form.cleaned_data['addressSend'] 
        profile.telephone = form.cleaned_data['telephone']
        profile.mobilePhone = form.cleaned_data['mobilePhone']
        user.save()
        profile.user = user
        profile.save()
        return super(register, self).form_valid(form)   
    
    
    
    
